package cn.calm.xhtml.impl.ui;

import java.util.Date;

import cn.calm.xhtml.annotation.Attribute;
import cn.calm.xhtml.annotation.Tag;
import cn.calm.xhtml.api.exception.XhtmlException;
import cn.calm.xhtml.api.service.AbstraceNodeProcess;
import cn.calm.xhtml.api.service.ResponseWriter;
import cn.calm.xhtml.api.service.XhtmlContext;
import cn.calm.xhtml.util.DateUtils;
@Tag(namespace = "http://www.calm.cn/xhtml/extras/ui", attributes = {
		@Attribute(name = "value", description = "展示值", template = "<label></label><input name=\"value\"/>"),
		@Attribute(name = "pattern", description = "时间展示模式", template = "<label></label><input name=\"pattern\"/>"),
		@Attribute(name = "length", description = "展示长度", template = "<label></label><input name=\"pattern\"/>")})
public class OutputText extends AbstraceNodeProcess {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String DEFAULT_ATTR_PATTERN = "pattern";
	public static final String DEFAULT_ATTR_LENGTH = "length";

	@Override
	public void processNode(XhtmlContext context) throws XhtmlException {
		Object value = getValue(context);
		if (value == null) {
			return;
		}
		ResponseWriter responseWriter = context.getResponseWriter();
		String displayValue;
		if (value instanceof Date) {
			String pattern = getAttr(DEFAULT_ATTR_PATTERN);
			if (pattern == null) {
				displayValue = value.toString();
			} else {
				String format = DateUtils.format((Date) value, pattern);
				displayValue = format;
			}

		} else {
			displayValue = value.toString();
		}
		String lengthStr = getAttr(DEFAULT_ATTR_LENGTH);
		if (lengthStr == null) {
			responseWriter.write(displayValue);
		} else {
			int length = Integer.parseInt(lengthStr);
			if (displayValue.length() > length) {
				String substring = displayValue.substring(0, length);
				responseWriter.write(substring);
				responseWriter.write("...");
			} else {
				responseWriter.write(displayValue);
			}
		}
	}

}
